<?php
/**
 * 个推消息推送 
 */
class Cli_SmsController extends Ctrl_Cli{
	public function indexAction(){
            exit;
		while(true){
            $tTime = time();
            $tRunlogdir = APPLICATION_PATH . '/shell/runlog/cli_sms.run';
            Tool_Fnc::writefile($tRunlogdir , $tTime);

			$this->sent();
			sleep(1);
		}
		exit;
	}
	private function sent(){
		$tRedis = Cache_Redis::instance();
		$tRes = $tRedis->rpop('supeibao_sms');	
		if(empty($tRes)){return ;}
		$tRow = unserialize($tRes);
        if(!count($tRow)){return false;}

        $apikey = Yaf_Registry::get("config")->yunpian->sms->apikey; //请用自己的apikey代替
        $mobile = $tRow['phone']; //请用自己的手机号代替
        $tpl_id = 1185505; //对应默认模板 【#company#】您的验证码是#code#
        $tpl_value = $tRow['content'];

        #print_r($tRow);
        $tRes = $this->tpl_send_sms($apikey,$tpl_id, $tpl_value, $mobile);
        #print_r($tRes);
 
	}


    //云片发送接口
    private function tpl_send_sms($apikey, $tpl_id, $tpl_value, $mobile){
        $url="http://yunpian.com/v1/sms/tpl_send.json";
        $encoded_tpl_value = urlencode("$tpl_value");  //tpl_value需整体转义
        $post_string="apikey=$apikey&tpl_id=$tpl_id&tpl_value=$encoded_tpl_value&mobile=$mobile";
        return json_decode($this->sock_post($url, $post_string),true);
    }
    private function sock_post($url,$query){
        $data = "";
        $info=parse_url($url);
        $fp=fsockopen($info["host"],80,$errno,$errstr,30);
        if(!$fp){
            return $data;
        }
        $head="POST ".$info['path']." HTTP/1.0\r\n";
        $head.="Host: ".$info['host']."\r\n";
        $head.="Referer: http://".$info['host'].$info['path']."\r\n";
        $head.="Content-type: application/x-www-form-urlencoded\r\n";
        $head.="Content-Length: ".strlen(trim($query))."\r\n";
        $head.="\r\n";
        $head.=trim($query);
        $write=fputs($fp,$head);
        $header = "";
        while ($str = trim(fgets($fp,4096))) {
            $header.=$str;
        }
        while (!feof($fp)) {
            $data .= fgets($fp,4096);
        }
        return $data;
    }

}
